# !/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2,urllib
import ssl

import urllib,urllib2
import ssl
import cookielib
from user import user,pwd
from codes import codes
from json import loads
from station import dealStat
from time import sleep
import re

header = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36'
}


#保存cookie
c= cookielib.LWPCookieJar()
cookie = urllib2.HTTPCookieProcessor(c)
opener =urllib2.build_opener(cookie)
urllib2.install_opener(opener)
##取消验证
ssl._create_default_https_context = ssl._create_unverified_context

##登录
def login():
    print("获取验证码")
    req = urllib2.Request('https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&0.666046139590464')
    req.headers = header
    imgCode = opener.open(req).read()
    with open('code.png', 'wb') as fn:
        fn.write(imgCode)

    req = urllib2.Request('https://kyfw.12306.cn/passport/captcha/captcha-check')
    #code = raw_input('input check: ')
    code = codes('code.png','287')
    print("识别验证码")
    data ={
        'answer': code,
        'login_site':'E',
        'rand':'sjrand'
    }
    par = urllib.urlencode(data)
    req.headers = header
    html = opener.open(req,par).read()
    print html
    req = urllib2.Request('https://kyfw.12306.cn/passport/web/login')
    data = {
        'username': user,
        'password':pwd,
        'appid': 'otn'
    }
    par = urllib.urlencode(data)
    req.headers = header
    html = opener.open(req, par).read()
    result = loads(html)

    #print(result)
    if(result['result_code']==0):
        print '-----登录success'
        # url1='https://kyfw.12306.cn/otn/login/userLogin'
        # data={
        #     '_json_att':''
        # }
        # req = urllib2.Request(url1)
        # req.headers = header
        # # print (dictData)
        # par = urllib.urlencode(data)
        # html = opener.open(req, par)
        # print (html.geturl())
        #
        # url2='https://kyfw.12306.cn/otn/passport?redirect=/otn/login/userLogin'
        # req = urllib2.Request(url2)
        # req.headers = header
        # html = opener.open(req)
        # print (html.geturl())

        url3='https://kyfw.12306.cn/passport/web/auth/uamtk'
        req = urllib2.Request(url3)
        req.headers = header
        # print (dictData)
        data = {
            'appid':'otn'
        }
        par1 = urllib.urlencode(data)

        html = opener.open(req,par1).read()
        #print(html)
        result = loads(html)
        tk = result['newapptk']
        print (tk)
        print(html)

        url5 = 'https://kyfw.12306.cn/otn/uamauthclient'
        req = urllib2.Request(url5)
        req.headers = header
        data = {
            'tk':tk
        }
        par1 = urllib.urlencode(data)
        html = opener.open(req,par1).read()


        url4='https://kyfw.12306.cn/otn/index/initMy12306'
        req = urllib2.Request(url4)
        req.headers = header
        html = opener.open(req).read()
        #print(html)
        return True;
    else:
        print '-----登录failure!!!!'
        login()
        sleep(5)

#login()
stlist = dealStat()
#出发日期
train_date ='2017-11-30'
#出发
from_stat='长沙'
from_station=stlist[from_stat]
#到达
to_stat='成都'
to_station=stlist[to_stat]
#成人或儿童
purpose_codes=''

##查询票
'''
#[3] = 车次
#[8] = 出发时间
#[9] = 到达时间
#[10] = 总用时
#[28] = 硬卧
#[32] = 商务座
#[31] = 一等座
#[30] = 二等座
#[23] = 软卧
#[24] = 软座
#[21] = 高级软卧
#[29] = 硬座
#[33] = 动卧
'''
def checkTicket():
    req = urllib2.Request('https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.'
                          'train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT' %(train_date,from_station,to_station))
    req.headers = header

    html = opener.open(req).read()
    result = loads(html)
    #print(result['data']['result'])
    train_ticket = result['data']['result']
    #车票词典，存储预订车票信息
    ticketDict={}


    #print(train_ticket)
    for i in train_ticket:
        tmplist = i.split('|')
        # index = 0
        # for k in tmplist:
        #print u'车次%s:' % (tmplist[3])
            # print index, k
            # index +=1
        if(tmplist[3]=='Z122'):
            print u'车次%s:' % (tmplist[3])
            #余票列表
            l = []
            # # 一等座
            # if (tmplist[31] == u'有' or tmplist[31].isdigit()):  # --或无
            #     print u'''一等座余票: %s''' % (tmplist[31])
            #     l.append(tmplist[31])
            # # 二等座
            # if (tmplist[30] == u'有' or tmplist[30].isdigit()):  # --或无
            #     print u'''二等座余票: %s''' % (tmplist[30])
            #     l.append(tmplist[30])
            # 软卧
            if (tmplist[23] == u'有' or tmplist[23].isdigit()):  # --或无
                print u'''软卧余票: %s''' % (tmplist[23])
                l.append(tmplist[23])

            # # 动卧
            # if (tmplist[33] == u'有' or tmplist[33].isdigit()):  # --或无
            #     print u'''动卧余票: %s''' % (tmplist[33])
            #     l.append(tmplist[33])
            # # 硬卧
            # if (tmplist[28] == u'有' or tmplist[28].isdigit()):  # --或无
            #     print u'''硬卧余票: %s''' % (tmplist[28])
            #     l.append(tmplist[28])
            # # 软座
            # if (tmplist[24] == u'有' or tmplist[24].isdigit()):  # --或无
            #     print u'''软座余票: %s''' % (tmplist[24])
            #     l.append(tmplist[24])
            # # 硬座
            # if (tmplist[29] == u'有' or tmplist[29].isdigit()):  # --或无
            #     print u'''硬座余票: %s''' % (tmplist[29])
            #     l.append(tmplist[29])
            if (len(l) == 0):
                print u'''无座或高等票'''
            else:
                l.insert(0,tmplist[0])
                ticketDict[tmplist[3]]=l
            #print(ticketDict)
    return ticketDict



#打开网址
def openUrl(url):
    req = urllib2.Request(url)
    req.headers = header
    html =opener.open(req).read()
    return html

'''
siteUrl:请求url
dictData:传递数据
'''
def openUrlWithData(siteUrl,dictData):
    req = urllib2.Request(siteUrl)
    req.headers = header
    #print (dictData)
    par = urllib.urlencode(dictData)
    html = opener.open(req, par).read()
    return html
#checkTicket()

def buyTicket():
    url = 'https://kyfw.12306.cn/otn/login/checkUser'
    data ={
        '_json_att' :''
    }
    html = openUrlWithData(url,data)
    print ("###下单1001###:"+html)
    lc = checkTicket()['Z122']

    secret=urllib.unquote(lc[0])
    print lc[0]
    print secret
    url = 'https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest'
    data = {

        'secretStr': secret,
    'train_date':train_date,
    'back_train_date':train_date,
    'tour_flag':'dc',
    'purpose_codes':'ADULT',
    'query_from_station_name':from_stat,
    'query_to_station_name':to_stat,
    'undefined':''
    }
    req = urllib2.Request(url)
    req.headers = header
    # print (dictData)
    par = urllib.urlencode(data)
    html = opener.open(req, par).read()

    print ('#####下单1002###:'+html)

    url = 'https://kyfw.12306.cn/otn/confirmPassenger/initDc'
    data = {
        '_json_att': ''
    }
    html = openUrlWithData(url, data)
    #print ("###下单1003###:" + html)

    REPEAT_SUBMIT_TOKEN=re.findall(r"globalRepeatSubmitToken = '(.*?)'",html)[0]
    print("###下单1003###:" +REPEAT_SUBMIT_TOKEN)

    url = 'https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs'
    data = {
        '_json_att': '',
        'REPEAT_SUBMIT_TOKEN:':REPEAT_SUBMIT_TOKEN
    }
    html = openUrlWithData(url, data)
    print ("###下单1004###:" + html)
    result = loads(html)
    #print (result['data']['normal_passengers'])
    print(result['data']['normal_passengers'][0])
    #print(type(result['data']['normal_passengers'][0]))
    print(result['data']['normal_passengers'][0]['passenger_name'])
    if(result['data']['normal_passengers'][0]['passenger_name']==u'杨浩'):
        print '###1005##',result['data']['normal_passengers'][0]['passenger_id_no'],result['data']['normal_passengers'][0]['mobile_no']
    # for i in result['data']['normal_passengers'][0]:
    #     print result['data']['normal_passengers']
        # if (result['data']['normal_passengers'][i]['passenger_name']==u'杨浩'):
        #     print result['data']['normal_passengers'][i]
    url ='https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo'
    data = {
        '_json_att': '',
        'REPEAT_SUBMIT_TOKEN:': REPEAT_SUBMIT_TOKEN,
        'cancel_flag':'2',
        'bed_level_order_num':'000000000000000000000000000000',
        'passengerTicketStr':'3,0,1,杨浩,1,110106198204170913,18910171654,N',
        'oldPassengerStr': '杨浩,1,110106198204170913,1_',
        'tour_flag':'dc',
        'randCode':''
    }
    html = openUrlWithData(url, data)
    print ("###下单1006###:" + html)

    url='https://kyfw.12306.cn/otn/confirmPassenger/confirmSingle'
    data={
        'passengerTicketStr':'3, 0, 1, 杨浩, 1, 110106198204170913, 18910171654, N',
    'oldPassengerStr':'杨浩, 1, 110106198204170913, 1_',
    'tour_flag':'dc',
    'randCode':'',
    'purpose_codes' :'00',
    'key_check_isChange':'3039D68B0D8AAFA22E6F33960E307C562684772ABBEC1D2E330E0FC0',
    'train_location': 'Q9',
    'choose_seats':'',
    'seatDetailType':'000',
    'roomType': '00',
    'dwAll':'N',
    '_json_att':'',
    'REPEAT_SUBMIT_TOKEN':'0e02dbbb6fdcd3b5e106e859e63e191a'
    }

login()
buyTicket()